﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;

namespace Sriram.GoogleProviders
{
    public class GoogleContext
    {
        //private members
        //private string _membershipspreadsheeturl;
        private string _GoogleID;
        private string _GooglePassword;
        //properties
        //private string MemberShipSpreadsheetUrl
        //{
        //    get { return _membershipspreadsheeturl; }
        //}

       //ctor

        public GoogleContext(string GoogleID, string GooglePassword)
        {
            _GoogleID = GoogleID;
            _GooglePassword = GooglePassword;
            Initialize();
        }
        

        
        public ListFeed GetGoogleSpreadsheetMembershipListFeed()
        {
            return GetGoogleSpreadsheetMembershipListFeed("");
        }

        public ListFeed GetGoogleSpreadsheetMembershipListFeed(string structuredquery)
        {
            ListFeed lfeed = null;
            bool IsMembershipSheetExits = false;
            //login logic
            SpreadsheetsService service = GetAuthenticatedSpreadsheetService();            
            SpreadsheetQuery query = new SpreadsheetQuery();
            SpreadsheetFeed feed = service.Query(query);
            //find spreadsheet named aspnetmembershipdatabase
            foreach (SpreadsheetEntry entry in feed.Entries)
            {
                if (entry.Title.Text == "ASPNetMembershipDatabase")
                {
                    IsMembershipSheetExits = true;
                    AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);
                   
                    WorksheetQuery wquery = new WorksheetQuery(link.HRef.ToString());
                    WorksheetFeed wfeed = service.Query(wquery);

                    //find workbook named users
                    foreach (WorksheetEntry worksheet in wfeed.Entries)
                    {
                        if (worksheet.Title.Text == "users")
                        {
                            AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
                            ListQuery lquery = new ListQuery(listFeedLink.HRef.ToString());
                            lquery.OrderByColumn = "username";
                            //check structuredquery not equal to empty
                            if (structuredquery != "")
                            {
                                //sample structuredquery "name=John and age>25"
                                lquery.SpreadsheetQuery = structuredquery;
                                
                                if (structuredquery.ToLower().Contains("email"))
                                {
                                    var email = structuredquery.Split('=')[1];
                                    lquery = new ListQuery(listFeedLink.HRef.ToString() + "?sq={email}%3d%22" + email + "%22");
                                    
                                }
                            }
                            
                            lfeed = service.Query(lquery);
                            break;
                            //foreach (ListEntry worksheetRow in feed.Entries)
                            //{
                            //    ListEntry.CustomElementCollection elements = worksheetRow.Elements;
                            //    foreach (ListEntry.Custom element in elements)
                            //    {
                            //        if (element.LocalName == "firstname")
                            //        {
                            //            //_firstname = element.Value;
                            //        }
                            //    }                               
                            //}
                        }
                    }
                }
                if (IsMembershipSheetExits)
                {
                    break;
                }
            }
            if (!IsMembershipSheetExits)
            {
                UploadSpreadsheet("ASPNetMembershipDatabase");
            }
            return lfeed;
            
        }
        
        //private methods
        private void Initialize()
        {
            ListFeed lfeed = GetGoogleSpreadsheetMembershipListFeed();            
        }
        private SpreadsheetsService GetAuthenticatedSpreadsheetService()
        {
            SpreadsheetsService myService = new SpreadsheetsService("Sriram-GoogleProviders-1");
            myService.setUserCredentials(_GoogleID, _GooglePassword);
            return myService;
        }
        private Google.GData.Documents.DocumentsService GetAuthenticatedDocumentListService()
        {
            Google.GData.Documents.DocumentsService myService = new Google.GData.Documents.DocumentsService("Sriram-GoogleProviders-1");
            myService.setUserCredentials(_GoogleID, _GooglePassword);
            return myService;
        }
        private void UploadSpreadsheet(string Sheetname)
        {
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            string newpath = path.Replace("file:\\", "");
            string fullpath = (newpath+ @"\" + Sheetname + ".xls").Replace("\\",@"\");
            Google.GData.Documents.DocumentsService myService = GetAuthenticatedDocumentListService();
            Google.GData.Documents.DocumentEntry newEntry = myService.UploadDocument( fullpath, "ASPNetMembershipDatabase");
            //return true;
        }      

    }

    
}
